/**
 * 俄罗斯方块游戏JavaScript实现
 * 包含游戏初始化、方块生成、移动、旋转、碰撞检测等核心逻辑
 */

// 游戏常量
const ROWS = 20;  // 游戏面板行数
const COLS = 10;  // 游戏面板列数
const BLOCK_SIZE = 30;  // 每个方块的大小（像素）
const EMPTY = 'white';  // 空白格颜色

// 方块类型及其颜色
const SHAPES = [
    [1, 1, 1, 1],     // I 形方块
    [1, 1, 1, 0,      // J 形方块
     0, 0, 1],
    [1, 1, 1, 0,      // L 形方块
     1, 0, 0],
    [1, 1, 0, 0,      // O 形方块
     1, 1],
    [0, 1, 1, 0,      // S 形方块
     1, 1],
    [0, 1, 0, 0,      // T 形方块
     1, 1, 1],
    [1, 1, 0, 0,      // Z 形方块
     0, 1, 1]
];

const COLORS = [
    '#00FFFF',  // 青色 - I 形方块
    '#0000FF',  // 蓝色 - J 形方块
    '#FFA500',  // 橙色 - L 形方块
    '#FFFF00',  // 黄色 - O 形方块
    '#00FF00',  // 绿色 - S 形方块
    '#800080',  // 紫色 - T 形方块
    '#FF0000'   // 红色 - Z 形方块
];

// 游戏变量
let board = [];  // 游戏面板
let currentPiece = null;  // 当前方块
let nextPiece = null;  // 下一个方块
let score = 0;  // 分数
debugger
let level = 1;  // 等级
let lines = 0;  // 已消除的行数
let gameInterval = null;  // 游戏主循环定时器
let paused = false;  // 游戏是否暂停
let gameOver = true;  // 游戏是否结束
let dropStart = 0;  // 方块下落起始时间

// DOM 元素
const gameCanvas = document.getElementById('game-board');
const gameContext = gameCanvas.getContext('2d');
const nextPieceCanvas = document.getElementById('next-piece-canvas');
const nextPieceContext = nextPieceCanvas.getContext('2d');
const scoreElement = document.getElementById('score');
const levelElement = document.getElementById('level');
const linesElement = document.getElementById('lines');
const startButton = document.getElementById('start-button');
const pauseButton = document.getElementById('pause-button');
const resetButton = document.getElementById('reset-button');

// 初始化游戏
function init() {
    // 初始化游戏面板
    createBoard();
    drawBoard();
    
    // 事件监听
    document.addEventListener('keydown', keyDownHandler);
    startButton.addEventListener('click', startGame);
    pauseButton.addEventListener('click', togglePause);
    resetButton.addEventListener('click', resetGame);
}

// 创建游戏面板
function createBoard() {
    board = [];
    for (let r = 0; r < ROWS; r++) {
        board[r] = [];
        for (let c = 0; c < COLS; c++) {
            board[r][c] = EMPTY;
        }
    }
}

// 绘制游戏面板
function drawBoard() {
    for (let r = 0; r < ROWS; r++) {
        for (let c = 0; c < COLS; c++) {
            drawBlock(c, r, board[r][c], gameContext, BLOCK_SIZE);
        }
    }
}

// 绘制方块
function drawBlock(x, y, color, ctx, blockSize) {
    ctx.fillStyle = color;
    ctx.fillRect(x * blockSize, y * blockSize, blockSize, blockSize);
    ctx.strokeStyle = '#333';
    ctx.strokeRect(x * blockSize, y * blockSize, blockSize, blockSize);
}

// 方块类
class Piece {
    constructor(shape, color) {
        this.shape = shape;
        this.color = color;
        
        // 计算方块的行列大小
        this.shapeRows = 0;
        this.shapeCols = 0;
        this.calculateShapeDimensions();
        
        // 设置初始位置（居中）
        this.x = Math.floor((COLS - this.shapeCols) / 2);
        this.y = 0;
        
        // 方块矩阵
        this.activeTetromino = this.createTetromino();
    }
    
    // 计算方块的行列大小
    calculateShapeDimensions() {
        if (this.shape.length === 4) {  // I 形方块
            this.shapeRows = 1;
            this.shapeCols = 4;
        } else if (this.shape.length === 7) {  // J 和 L 形方块
            this.shapeRows = 2;
            this.shapeCols = 3;
        } else if (this.shape.length === 6) {  // O, S, T, Z 形方块
            this.shapeRows = 2;
            this.shapeCols = 2;
            if (this.shape[0] === 0 || this.shape[2] === 0) {  // S, T, Z 形方块
                this.shapeRows = 2;
                this.shapeCols = 3;
            }
        }
    }
    
    // 创建方块矩阵
    createTetromino() {
        const tetromino = [];
        let index = 0;
        
        if (this.shape.length === 4) {  // I 形方块
            tetromino[0] = [this.shape[0], this.shape[1], this.shape[2], this.shape[3]];
        } else if (this.shape.length === 7) {  // J 和 L 形方块
            tetromino[0] = [this.shape[0], this.shape[1], this.shape[2]];
            tetromino[1] = [this.shape[3], this.shape[4], this.shape[5]];
        } else if (this.shape.length === 6) {  // O, S, T, Z 形方块
            if (this.shape.toString() === [1,1,0,0,1,1].toString()) {  // O 形方块
                tetromino[0] = [this.shape[0], this.shape[1]];
                tetromino[1] = [this.shape[2], this.shape[3]];
            } else {  // S, T, Z 形方块
                tetromino[0] = [this.shape[0], this.shape[1], this.shape[2]];
                tetromino[1] = [this.shape[3], this.shape[4], this.shape[5]];
            }
        }
        
        return tetromino;
    }
    
    // 绘制方块
    draw() {
        for (let r = 0; r < this.activeTetromino.length; r++) {
            for (let c = 0; c < this.activeTetromino[r].length; c++) {
                if (this.activeTetromino[r][c]) {
                    drawBlock(this.x + c, this.y + r, this.color, gameContext, BLOCK_SIZE);
                }
            }
        }
    }
    
    // 清除方块
    undraw() {
        for (let r = 0; r < this.activeTetromino.length; r++) {
            for (let c = 0; c < this.activeTetromino[r].length; c++) {
                if (this.activeTetromino[r][c]) {
                    drawBlock(this.x + c, this.y + r, EMPTY, gameContext, BLOCK_SIZE);
                }
            }
        }
    }
    
    // 向下移动
    moveDown() {
        if (!this.collision(0, 1, this.activeTetromino)) {
            this.undraw();
            this.y++;
            this.draw();
            return true;
        }
        this.lock();
        return false;
    }
    
    // 向左移动
    moveLeft() {
        if (!this.collision(-1, 0, this.activeTetromino)) {
            this.undraw();
            this.x--;
            this.draw();
        }
    }
    
    // 向右移动
    moveRight() {
        if (!this.collision(1, 0, this.activeTetromino)) {
            this.undraw();
            this.x++;
            this.draw();
        }
    }
    
    // 旋转方块
    rotate() {
        const nextPattern = this.transposeMatrix(this.activeTetromino);
        const rotated = this.reverseRows(nextPattern);
        
        if (!this.collision(0, 0, rotated)) {
            this.undraw();
            this.activeTetromino = rotated;
            this.draw();
        }
    }
    
    // 矩阵转置
    transposeMatrix(matrix) {
        const newMatrix = [];
        for (let c = 0; c < matrix[0].length; c++) {
            newMatrix[c] = [];
            for (let r = 0; r < matrix.length; r++) {
                newMatrix[c][r] = matrix[r][c];
            }
        }
        return newMatrix;
    }
    
    // 矩阵行反转
    reverseRows(matrix) {
        return matrix.map(row => row.reverse());
    }
    
    // 碰撞检测
    collision(x, y, piece) {
        for (let r = 0; r < piece.length; r++) {
            for (let c = 0; c < piece[r].length; c++) {
                if (!piece[r][c]) continue;
                
                const newX = this.x + c + x;
                const newY = this.y + r + y;
                
                // 检查边界
                if (newX < 0 || newX >= COLS || newY >= ROWS) {
                    return true;
                }
                
                // 忽略上边界
                if (newY < 0) continue;
                
                // 检查已有方块
                if (board[newY][newX] !== EMPTY) {
                    return true;
                }
            }
        }
        return false;
    }
    
    // 锁定方块
    lock() {
        for (let r = 0; r < this.activeTetromino.length; r++) {
            for (let c = 0; c < this.activeTetromino[r].length; c++) {
                if (!this.activeTetromino[r][c]) continue;
                
                // 游戏结束检测
                if (this.y + r < 0) {
                    endGame();
                    return;
                }
                
                // 更新游戏面板
                board[this.y + r][this.x + c] = this.color;
            }
        }
        
        // 检查并消除行
        let clearedLines = 0;
        for (let r = 0; r < ROWS; r++) {
            let isRowFull = true;
            for (let c = 0; c < COLS; c++) {
                isRowFull = isRowFull && (board[r][c] !== EMPTY);
            }
            
            if (isRowFull) {
                // 消除行
                clearRow(r);
                clearedLines++;
            }
        }
        
        // 更新分数
        if (clearedLines > 0) {
            updateScore(clearedLines);
        }
        
        // 生成新方块
        generatePiece();
    }
}

// 消除行
function clearRow(row) {
    // 将上方行向下移动
    for (let r = row; r > 0; r--) {
        for (let c = 0; c < COLS; c++) {
            board[r][c] = board[r-1][c];
        }
    }
    
    // 清空最上面一行
    for (let c = 0; c < COLS; c++) {
        board[0][c] = EMPTY;
    }
    
    // 重绘游戏面板
    drawBoard();
}

// 更新分数
function updateScore(clearedLines) {
    // 根据消除行数计算得分
    const lineScores = [40, 100, 300, 1200];
    score += lineScores[clearedLines - 1] * level;
    
    // 更新总消除行数
    lines += clearedLines;
    
    // 更新等级（每10行提升一级）
    const newLevel = Math.floor(lines / 10) + 1;
    if (newLevel > level) {
        level = newLevel;
        // 提高游戏速度
        clearInterval(gameInterval);
        const speed = 1000 - (level - 1) * 100;
        gameInterval = setInterval(gameLoop, Math.max(100, speed));
    }
    
    // 更新显示
    scoreElement.textContent = score;
    levelElement.textContent = level;
    linesElement.textContent = lines;
}

// 随机生成方块
function generatePiece() {
    if (nextPiece === null) {
        const randomIndex = Math.floor(Math.random() * SHAPES.length);
        nextPiece = new Piece(SHAPES[randomIndex], COLORS[randomIndex]);
    }
    
    currentPiece = nextPiece;
    
    // 生成下一个方块
    const randomIndex = Math.floor(Math.random() * SHAPES.length);
    nextPiece = new Piece(SHAPES[randomIndex], COLORS[randomIndex]);
    
    // 绘制下一个方块预览
    drawNextPiece();
}

// 绘制下一个方块预览
function drawNextPiece() {
    // 清空画布
    nextPieceContext.fillStyle = EMPTY;
    nextPieceContext.fillRect(0, 0, nextPieceCanvas.width, nextPieceCanvas.height);
    
    // 计算居中位置
    const offsetX = (nextPieceCanvas.width / BLOCK_SIZE - nextPiece.activeTetromino[0].length) / 2;
    const offsetY = (nextPieceCanvas.height / BLOCK_SIZE - nextPiece.activeTetromino.length) / 2;
    
    // 绘制下一个方块
    for (let r = 0; r < nextPiece.activeTetromino.length; r++) {
        for (let c = 0; c < nextPiece.activeTetromino[r].length; c++) {
            if (nextPiece.activeTetromino[r][c]) {
                drawBlock(offsetX + c, offsetY + r, nextPiece.color, nextPieceContext, BLOCK_SIZE / 1.5);
            }
        }
    }
}

// 键盘事件处理
function keyDownHandler(event) {
    if (gameOver || paused) return;
    
    if (event.keyCode === 37) {  // 左箭头
        currentPiece.moveLeft();
        dropStart = Date.now();
    } else if (event.keyCode === 38) {  // 上箭头
        currentPiece.rotate();
        dropStart = Date.now();
    } else if (event.keyCode === 39) {  // 右箭头
        currentPiece.moveRight();
        dropStart = Date.now();
    } else if (event.keyCode === 40) {  // 下箭头
        currentPiece.moveDown();
    } else if (event.keyCode === 32) {  // 空格
        // 直接落到底部
        while (currentPiece.moveDown()) { }
    } else if (event.keyCode === 80) {  // P键
        togglePause();
    }
}

// 游戏主循环
function gameLoop() {
    if (gameOver || paused) return;
    
    const now = Date.now();
    const delta = now - dropStart;
    
    // 根据等级计算下落速度
    const speed = 1000 - (level - 1) * 100;
    
    if (delta > speed) {
        currentPiece.moveDown();
        dropStart = now;
    }
}

// 开始游戏
function startGame() {
    if (!gameOver) return;
    
    // 重置游戏状态
    resetGame();
    
    // 开始游戏循环
    gameOver = false;
    generatePiece();
    dropStart = Date.now();
    
    // 设置游戏速度
    const speed = 1000 - (level - 1) * 100;
    gameInterval = setInterval(gameLoop, speed);
    
    // 更新按钮状态
    startButton.disabled = true;
    pauseButton.disabled = false;
    resetButton.disabled = false;
}

// 暂停/继续游戏
function togglePause() {
    if (gameOver) return;
    
    paused = !paused;
    
    if (paused) {
        pauseButton.textContent = '继续';
    } else {
        pauseButton.textContent = '暂停';
        dropStart = Date.now();
    }
}

// 重置游戏
function resetGame() {
    // 清除游戏循环
    clearInterval(gameInterval);
    
    // 重置游戏状态
    createBoard();
    drawBoard();
    score = 0;
    level = 1;
    lines = 0;
    gameOver = true;
    paused = false;
    currentPiece = null;
    nextPiece = null;
    
    // 更新显示
    scoreElement.textContent = score;
    levelElement.textContent = level;
    linesElement.textContent = lines;
    
    // 更新按钮状态
    startButton.disabled = false;
    pauseButton.disabled = true;
    pauseButton.textContent = '暂停';
    resetButton.disabled = true;
}

// 游戏结束
function endGame() {
    gameOver = true;
    clearInterval(gameInterval);
    
    // 显示游戏结束提示
    gameContext.fillStyle = 'rgba(0, 0, 0, 0.5)';
    gameContext.fillRect(0, 0, gameCanvas.width, gameCanvas.height);
    
    gameContext.font = 'bold 30px Arial';
    gameContext.fillStyle = 'white';
    gameContext.textAlign = 'center';
    gameContext.textBaseline = 'middle';
    gameContext.fillText('游戏结束', gameCanvas.width / 2, gameCanvas.height / 2 - 30);
    
    gameContext.font = '20px Arial';
    gameContext.fillText(`最终得分: ${score}`, gameCanvas.width / 2, gameCanvas.height / 2 + 10);
    gameContext.fillText('点击"开始游戏"重新开始', gameCanvas.width / 2, gameCanvas.height / 2 + 50);
    
    // 更新按钮状态
    startButton.disabled = false;
    pauseButton.disabled = true;
}

// 初始化游戏
window.onload = function() {
    init();
    resetGame();
}; 